package cmd

import (
	"context"
	"testing"
	"time"

	"github.com/bruin-data/bruin/pkg/pipeline"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
)

func BenchmarkLint(b *testing.B) {
	isDebug := false
	cmd := Lint(&isDebug)

	for range [10]int{} {
		b.ResetTimer()
		start := time.Now()
		if err := cmd.Run(b.Context(), []string{"lint", "./testdata/lineage"}); err != nil {
			b.Fatalf("Failed to run Lint command: %v", err)
		}
		b.StopTimer()
		if time.Since(start) > 200*time.Millisecond {
			b.Fatalf("Benchmark took longer than 100ms")
		}
	}
}

func Test_unwrapAllErrors(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		err  error
		want []string
	}{
		{
			name: "nil error",
			err:  nil,
			want: []string{},
		},
		{
			name: "single error",
			err:  errors.New("single error"),
			want: []string{"single error"},
		},
		{
			name: "nested errors",
			err:  errors.Wrap(errors.Wrapf(errors.New("inner error"), "%s error", "middle"), "outer error"),
			want: []string{"outer error", "middle error", "inner error"},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			got := unwrapAllErrors(tt.err)
			assert.Equal(t, tt.want, got)
		})
	}
}

func TestLintFullRefreshFlag(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name           string
		fullRefresh    bool
		expectedCtxKey interface{}
		expectedValue  interface{}
	}{
		{
			name:           "full refresh enabled",
			fullRefresh:    true,
			expectedCtxKey: pipeline.RunConfigFullRefresh,
			expectedValue:  true,
		},
		{
			name:           "full refresh disabled",
			fullRefresh:    false,
			expectedCtxKey: pipeline.RunConfigFullRefresh,
			expectedValue:  false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			ctx := t.Context()
			lintCtx := context.WithValue(ctx, pipeline.RunConfigFullRefresh, tt.fullRefresh)
			actualValue := lintCtx.Value(tt.expectedCtxKey)
			assert.Equal(t, tt.expectedValue, actualValue, "Context should contain correct full refresh value")
		})
	}
}
